<template>
  <div class="index">
    <!-- 标题 -->
    <module-title :title="moduleTitle"></module-title>

    <!-- 话术搜索 start -->
    <el-card>
      <div class="card-title">话术搜索</div>
      <!-- 搜索 -->
      <div class="query">
        <div>
          <span>话术名称：</span>
          <el-input
            style="width: 228px"
            v-model="queryWordsForm.name"
          ></el-input>
        </div>
        <div style="margin-left: 45px">
          <span>状态：</span>
          <el-select v-model="queryWordsForm.enabled" placeholder="请选择">
            <el-option
              v-for="item in enabledOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div style="margin-left: 45px">
          <el-button class="query-button" @click="queryBtnClick()"
            >搜索</el-button
          >
          <el-button class="clear-button" @click="clearQueryData()"
            >清空条件</el-button
          >
        </div>
      </div>
      <!-- 列表 -->
      <div class="list" style="margin-top: 50px">
        <div class="list-header">
          <span
            style="width: 4%; border-right: 1px solid #d9d9d9; font-weight: 700; color: #1074fd"
          >
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
            ></el-checkbox>
          </span>
          <span
            style="width: 10%; border-right: 1px solid #d9d9d9; font-weight: 700; color: #1074fd"
            >编号</span
          >
          <span
            style="width: 21%; border-right: 1px solid #d9d9d9; font-weight: 700; color: #1074fd"
            >话术名称</span
          >
          <span
            style="width: 42%; border-right: 1px solid #d9d9d9; font-weight: 700; color: #1074fd"
            >内容</span
          >
          <span
            style="width: 11%; border-right: 1px solid #d9d9d9; font-weight: 700; color: #1074fd"
            >操作</span
          >
          <span style="width: 12%; font-weight: 700; color: #1074fd">状态</span>
        </div>
        <div v-if="list.length > 0">
          <el-checkbox-group
            v-model="checkedOptions"
            @change="handleCheckedOptionsChange"
          >
            <div class="list-body" v-for="(item, index) in list" :key="item.id">
              <span
                style="width: 4%; border-right: 1px solid #d9d9d9; color: #4d4d4d; font-size: 14px"
              >
                <el-checkbox :label="item.id"></el-checkbox>
              </span>
              <span
                style="width: 10%; border-right: 1px solid #d9d9d9; color: #4d4d4d; font-size: 14px"
              >
                {{ index + 1 }}
              </span>
              <span
                style="width: 21%; border-right: 1px solid #d9d9d9; color: #4d4d4d; font-size: 14px"
              >
                {{ item.name }}
              </span>
              <span
                @click="wordsContentDetailBtnClick(index)"
                class="words-content"
                style="width: 26%; border-right: 1px solid #d9d9d9; color: #4d4d4d; font-size: 14px"
              >
                {{ item.contents }}
              </span>
              <span
                @click="modifyWordsBtnClick(index)"
                style="width: 11%; border-right: 1px solid #d9d9d9; color: #1074FD; font-size: 14px; cursor: pointer;"
              >
                修改
              </span>
              <span style="width: 12%; color: #4d4d4d; font-size: 14px;">
                <el-switch
                  v-model="item.enabled"
                  active-color="#1074FD"
                  inactive-color="#aaa"
                  active-text="启用"
                  inactive-text="禁用"
                  :width="60"
                  @change="enabledWords(item)"
                >
                </el-switch>
              </span>
            </div>
          </el-checkbox-group>
        </div>
        <div class="noneList" v-else>当前暂无行业数据</div>
      </div>
      <!-- 分页 -->
      <div>
        <div style="text-align: center; margin-top: 10px">
          <el-pagination
            :page-size="6"
            :pager-count="5"
            layout="total, prev, pager, next"
            :total="total"
            @prev-click="paginationPrevClick"
            @next-click="paginationNextClick"
            @current-change="paginationNextChange"
          ></el-pagination>
        </div>
      </div>
      <!-- 按钮 -->
      <div style="text-align: right; margin-top: 20px">
        <el-button class="clear-button" @click="delWords()">删除</el-button>
        <el-button class="query-button" @click="addWordsDialog = true"
          >新增</el-button
        >
      </div>
    </el-card>
    <!-- 话术搜索 end -->

    <!-- 弹窗 -->
    <!-- 新增话术 start -->
    <el-dialog
      title="新增话术"
      width="40%"
      center
      :visible.sync="addWordsDialog"
    >
      <el-form
        ref="addWordsForm"
        size="mini"
        style="width:90%;margin: 0 auto "
        :model="addWordsFormCopy"
      >
        <el-form-item
          :rules="{
            required: true,
            message: '请输入话术名称',
            trigger: 'blur'
          }"
          label-width="80px"
          label="话术名称"
          prop="wordsTitle"
        >
          <el-input
            v-model="addWordsFormCopy.wordsTitle"
            style="width: 80%"
            autocomplete="off"
            @change="queryWordsSen"
          ></el-input>
        </el-form-item>
        <el-divider />
        <el-row
          v-for="(item, index) in addWordsFormCopy.wordsList"
          :key="index"
        >
          <el-form-item
            :rules="{
              required: true,
              message: '请输入话术内容',
              trigger: 'blur'
            }"
            label-width="40px"
            :label="String(index + 1)"
            :prop="'wordsList[' + index + ']'"
          >
            <el-input
              v-model="addWordsFormCopy.wordsList[index]"
              autocomplete="off"
              @change="queryWordsSenes(index)"
            ></el-input>
          </el-form-item>
        </el-row>
        <div class="add-one-word-button" @click="addOneWord()">
          +
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addWordsCancel()">取 消</el-button>
        <el-button type="primary" @click="addWordsConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增话术 end -->

    <!-- 修改话术 start -->
    <el-dialog
      title="修改话术"
      width="40%"
      center
      :visible.sync="modifyWordsDialog"
    >
      <el-form
        ref="modifyWordsForm"
        size="mini"
        style="width:90%;margin: 0 auto "
        :model="modifyWordsForm"
      >
        <el-form-item label-width="80px" label="话术名称" prop="name">
          <el-input
            disabled
            v-model="modifyWordsForm.name"
            style="width: 80%"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-divider />
        <el-row v-for="(item, index) in modifyWordsForm.contents" :key="index">
          <el-form-item
            :rules="{
              required: true,
              message: '请输入话术内容',
              trigger: 'blur'
            }"
            label-width="40px"
            :label="String(index + 1)"
            :prop="'contents[' + index + ']'"
          >
            <el-input
              v-model="modifyWordsForm.contents[index]"
              autocomplete="off"
              >{{ item[index] }}</el-input
            >
          </el-form-item>
        </el-row>
        <div class="add-one-word-button" @click="addModifyOneWord()">
          +
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyWordsDialog = false">取 消</el-button>
        <el-button type="primary" @click="modifyWords()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改话术 end -->

    <!-- 话术详情 start -->
    <el-dialog
      :title="wordsTitle"
      :visible.sync="wordsDetailDialog"
      center
      width="40%"
    >
      <div
        style="margin: 0 20px 10px; display: flex"
        v-for="(item, idx) in currentWordsList"
        :key="idx"
      >
        <span style="width: 10%; font-weight: 700">{{ idx + 1 }}</span>
        <span style="color: #999">{{ item }}</span>
      </div>
    </el-dialog>
    <!-- 话术详情 start -->
  </div>
</template>

<script>
import { createSign } from "@/utils/sign";
import API from "@/network/api/emsApi";
import ModuleTitle from "@/components/content/ModuleTitle.vue";
export default {
  name: "index",
  data() {
    return {
      SensitiveWords: [],
      moduleTitle: "话术设置",
      addWordsDialog: false, // 新增话术弹窗
      modifyWordsDialog: false, // 修改话术弹窗
      wordsDetailDialog: false, // 话术详情弹窗
      total: 0,
      enable: true, // 是否启用
      list: [], // 话术列表
      wordsList: [], // 话术内容列表
      wordsTitle: "", // 话术详情标题
      currentWordsList: [], // 当前话术详情列表
      checkAll: false,
      isIndeterminate: false,
      options: [],
      enabledOptions: [
        {
          value: true,
          label: "启用"
        },
        {
          value: false,
          label: "禁用"
        }
      ],
      checkedOptions: [],
      // 新增话术参数
      addWordsForm: {
        name: "",
        contents: "",
        organId: 0
      },
      // 新增话术参数副本
      addWordsFormCopy: {
        wordsTitle: "",
        wordsList: ["", "", ""]
      },
      // 条件查询参数
      queryWordsForm: {
        name: "",
        enabled: ""
      },
      queryWordsFormCopy: {},
      // 查询参数
      queryForm: {
        organId: 0,
        pageNum: 1,
        pageSize: 6
      },
      // 修改话术参数
      modifyWordsForm: {
        contents: []
      },
      // 公共参数
      publicForm: {
        timestamp: ""
      }
    };
  },
  created() {
    this.currentUserInfo = JSON.parse(localStorage.getItem("updateUserInfo"));
    this.queryWords();
    API.querySensitiveWords().then(res => {
      console.log(res);
      this.SensitiveWords = res.data.data
    })
  },
  methods: {
    /**
     * 逻辑
     */
    queryWordsSen () {
      this.SensitiveWords.forEach(item => {
        if (this.addWordsFormCopy.wordsTitle.indexOf(item) !== -1) {
          alert('检测到有敏感词！请重新输入')
          this.addWordsFormCopy.wordsTitle = ''
        }
      })
    },
    queryWordsSenes (index) {
      this.SensitiveWords.forEach(item => {
        if (this.addWordsFormCopy.wordsList[index].indexOf(item) !== -1) {
          alert('检测到有敏感词！请重新输入')
          this.addWordsFormCopy.wordsList[index] = ''
        }
      })
    },
    // 条件查询
    queryBtnClick() {
      if (this.queryWordsFormCopy.name) {
        delete this.queryWordsFormCopy.name;
      }
      if (this.queryWordsForm.name !== "") {
        this.queryWordsFormCopy.name = this.queryWordsForm.name;
      }
      if (typeof this.queryWordsForm.enabled === "boolean") {
        this.queryWordsFormCopy.enabled = this.queryWordsForm.enabled ? 1 : 0;
      }
      this.queryWords();
    },

    // 清空条件
    clearQueryData() {
      this.queryWordsForm = this.queryWordsFormCopy = {};
      this.queryWords();
    },

    // 多选/全选删除
    handleCheckAllChange(val) {
      this.checkedOptions = val ? this.options : [];
      this.isIndeterminate = false;
    },
    handleCheckedOptionsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.options.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.options.length;
    },

    // 话术详情
    wordsContentDetailBtnClick(index) {
      this.wordsDetailDialog = true;
      this.wordsTitle = this.list[index].name;
      this.currentWordsList = this.wordsList[index];
    },
    // 修改话术
    modifyWordsBtnClick(index) {
      this.modifyWordsForm.name = this.list[index].name;
      this.modifyWordsForm.contents = this.wordsList[index];
      this.modifyWordsForm.id = this.list[index].id;
      this.modifyWordsDialog = true;
    },

    // 新增话术
    addWordsConfirm() {
      this.$refs.addWordsForm.validate(valid => {
        if (valid) {
          this.addWords();
        }
      });
    },

    // 新增一条话术栏
    addOneWord() {
      this.addWordsFormCopy.wordsList.push("");
    },
    addModifyOneWord() {
      this.modifyWordsForm.contents.push("");
    },

    // 取消新增
    addWordsCancel() {
      this.addWordsDialog = false;
      this.$refs.addWordsForm.resetFields();
      this.addWordsFormCopy.wordsList = ["", "", ""];
    },

    // 分页
    paginationPrevClick(page) {
      this.currentPage = page;
      this.queryForm.pageNum = page;
      this.queryWords();
    },
    paginationNextClick(page) {
      this.currentPage = page;
      this.queryForm.pageNum = page;
      this.queryWords();
    },
    paginationNextChange(page) {
      this.currentPage = page;
      this.queryForm.pageNum = page;
      this.queryWords();
    },

    /**
     * 网络请求
     */

    // 新增话术
    async addWords() {
      this.addWordsForm.name = this.addWordsFormCopy.wordsTitle;
      for (let i = 0; i < this.addWordsFormCopy.wordsList.length; i++) {
        this.addWordsForm.contents += this.addWordsFormCopy.wordsList[i];
        this.addWordsForm.contents += "%&*$*&%";
      }
      this.addWordsForm.contents = this.addWordsForm.contents.substring(
        0,
        this.addWordsForm.contents.length - 7
      );
      this.addWordsForm.organId = this.currentUserInfo.organId;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...this.addWordsForm,
          ...this.publicForm
        })
      );
      await API.getWordsAdd({
        ...this.addWordsForm,
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          this.$message.success("添加成功");
        } else {
          this.$message.warning(res.data.msg);
        }
      });
      this.addWordsDialog = false;
      this.addWordsForm.contents = "";
      this.$refs.addWordsForm.resetFields();
      this.addWordsFormCopy.wordsList = ["", "", ""];
      this.queryWords();
    },

    // 查询话术
    async queryWords() {
      this.queryForm.organId = this.currentUserInfo.organId;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...this.queryForm,
          ...this.publicForm,
          ...this.queryWordsFormCopy
        })
      );
      await API.getWordsQuery({
        ...this.publicForm,
        ...this.queryForm,
        ...this.queryWordsFormCopy
      }).then(res => {
        if (res.data.code === 0) {
          this.wordsList = [];
          this.list = res.data.data.records;
          this.total = res.data.data.total;
          for (let k in this.list) {
            let arr = [];
            this.options.push(this.list[k].id);
            arr = this.list[k].contents.split("%&*$*&%");
            this.wordsList.push(arr);
            this.list[k].contents = this.list[k].contents.replaceAll(
              "%&*$*&%",
              ","
            );
            this.list[k].enabled = Boolean(this.list[k].enabled);
          }
        } else {
          this.$message.warning(res.data.msg);
        }
      });
    },

    // 修改话术
    async modifyWords() {
      this.$refs.modifyWordsForm.validate(async valid => {
        if (valid) {
          let modForm = {
            contents: "",
            id: 0
          };
          modForm.id = this.modifyWordsForm.id;
          for (let i = 0; i < this.modifyWordsForm.contents.length; i++) {
            modForm.contents += this.modifyWordsForm.contents[i];
            modForm.contents += "%&*$*&%";
          }
          modForm.contents = modForm.contents.substring(
            0,
            modForm.contents.length - 7
          );
          this.publicForm.timestamp = +new Date();
          if (this.publicForm.sign) {
            delete this.publicForm.sign;
          }
          this.publicForm.sign = createSign(
            JSON.stringify({
              ...this.publicForm,
              ...modForm
            })
          );
          await API.getWordsUpd({
            ...modForm,
            ...this.publicForm
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("修改成功");
            } else {
              this.$message.warning(res.data.msg);
            }
          });
          this.modifyWordsDialog = false;
          this.queryWords();
        }
      });
    },

    // 删除话术
    async delWords() {
      let ids = this.checkedOptions;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({ ids, ...this.publicForm })
      );
      await API.getWordsDel({
        ids,
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          this.$message.success("删除成功");
        } else {
          this.$message.warning(res.data.msg);
        }
      });
      this.queryWords();
    },

    // 禁用/启用话术
    async enabledWords(item) {
      let modForm = {};
      modForm.id = item.id;
      modForm.enabled = item.enabled ? 1 : 0;
      this.publicForm.timestamp = +new Date();
      if (this.publicForm.sign) {
        delete this.publicForm.sign;
      }
      this.publicForm.sign = createSign(
        JSON.stringify({
          ...modForm,
          ...this.publicForm
        })
      );
      await API.getWordsUpd({
        ...modForm,
        ...this.publicForm
      }).then(res => {
        if (res.data.code === 0) {
          if (item.enabled) {
            this.$message.success("启用成功");
          } else {
            this.$message.success("禁用成功");
          }
        } else {
          this.$message.warning(res.data.msg);
        }
      });
      this.queryWords();
    }
  },
  components: { ModuleTitle }
};
</script>

<style scoped>
* {
  box-sizing: content-box;
}
.card-title {
  color: #1074fd;
  font-size: 18px;
  margin-bottom: 14px;
}

/* 搜索 */
.query {
  display: flex;
}
.query-button {
  border-radius: 4px;
  background-color: #1074fd;
  color: #fff;
}
.clear-button {
  border-radius: 4px;
  background-color: #fff;
  color: #666666;
}

/* 列表 */
.list {
  position: relative;
  width: 100%;
  height: 356px;
  border: 1px solid #d9d9d9;
}
.list-header {
  display: flex;
  height: 50px;
  background-color: #f2f2f2;
  border-bottom: 1px solid #d9d9d9;
  text-align: center;
  line-height: 50px;
}
.list-body {
  display: flex;
  height: 50px;
  border-bottom: 1px solid #d9d9d9;
  text-align: center;
  line-height: 50px;
}

/deep/.list-body .el-checkbox__label {
  color: transparent;
  padding: 0;
  margin: 0;
  margin-left: -7px;
}

/* 话术 */
.words-content {
  pointer-events: none; /* 关闭元素点击事件 */
  position: relative;
  padding: 0 8%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.words-content::after {
  content: "...";
  pointer-events: auto; /* 给伪元素开启事件 */
  cursor: pointer;
  position: absolute;
  right: 19px;
  top: 17px;
  width: 14px;
  z-index: 9;
  height: 14px;
  text-align: center;
  line-height: 7px;
  font-size: 14px;
  color: #ccc;
  border: 1px solid #ccc;
  border-radius: 14px;
}

/* 滑动按钮 */

/deep/ .list-body .el-switch__label--left {
  position: relative;
  left: 57px;
  color: #fff;
  user-select: none;
  z-index: -1111;
}
/deep/ .list-body .el-switch__label--right {
  position: relative;
  right: 57px;
  color: #fff;
  user-select: none;
  z-index: -1111;
}
/deep/ .list-body .el-switch__label.is-active {
  z-index: 1111;
  color: #fff;
}

/* 添加一条话术按钮 */
.add-one-word-button {
  height: 30px;
  width: 100%;
  cursor: pointer;
  user-select: none;
  line-height: 30px;
  background-color: #eee;
  border-radius: 4px;
  font-size: 40px;
  color: #ccc;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

.noneList {
  position: relative;
  width: 100%;
  height: 300px;
  margin: 0 auto 40px;
  text-align: center;
  line-height: 300px;
  font-size: 30px;
}
</style>
